package com.xiaochun.jiankangapp.activity

import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import androidx.core.view.children
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.luck.picture.lib.PictureSelectorFragment
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.xiaochun.jiankangapp.R
import com.xiaochun.jiankangapp.base.BaseActivity
import com.xiaochun.jiankangapp.databinding.ActivitySendReportBinding
import com.xiaochun.jiankangapp.databinding.ListItemUploadFileBinding
import com.xiaochun.jiankangapp.dialog.ChooseGalleryDialog
import com.xiaochun.jiankangapp.extension.loadUrl
import com.xiaochun.jiankangapp.extension.onClick
import com.xiaochun.jiankangapp.extension.showToast
import com.xiaochun.jiankangapp.model.ReportFileModel
import com.xiaochun.jiankangapp.network.Request
import com.xiaochun.jiankangapp.utils.GlideEngine
import com.xiaochun.jiankangapp.utils.UriUtils
import com.xiaochun.jiankangapp.viewmodel.SendReportViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class SendReportActivity : BaseActivity() {
    lateinit var viewBinding: ActivitySendReportBinding
    private val viewModel: SendReportViewModel by viewModels()
    private val list = mutableListOf<ReportFileModel>()
    private val adapter by lazy {
        UploadFileAdapter()
    }
    private val p = registerForActivityResult(ActivityResultContracts.PickVisualMedia(), object :
        ActivityResultCallback<Uri?> {
        override fun onActivityResult(result: Uri?) {
            result?.let {
                val file = UriUtils.uriToFile(this@SendReportActivity, it)
                file?.absolutePath?.apply {
                    uploadFile(ReportFileModel(this))

                }
            }
        }
    })
    private var lastUri: File? = null
    private val camera = registerForActivityResult(ActivityResultContracts.TakePicture(), object :
        ActivityResultCallback<Boolean?> {

        override fun onActivityResult(result: Boolean?) {
            if (result == true) {
                lastUri?.let {
                    it.absolutePath?.apply {
                        uploadFile(ReportFileModel(this))

                    }
                }
            }
        }
    })

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        lastUri?.let {
            outState.putSerializable("uri", it)
        }
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        lastUri = savedInstanceState.getSerializable("uri") as File?
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBinding = setContentView()
        viewBinding.add.onClick {
            showSelectDialog()
//            pictureSelector()
//            p.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
//            startActivityForResult(Intent(this, ReportFileActivity::class.java), 1000)
        }
        viewBinding.btnAdd.onClick {
            showSelectDialog()
//            pictureSelector()
//            p.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
//            startActivityForResult(Intent(this, ReportFileActivity::class.java), 1000)
        }
        viewBinding.rv.adapter = adapter
        viewBinding.save.onClick {
            if (list.isEmpty()) {
                return@onClick
            }

            lifecycleScope.launch {
                showLoading()
                val l = mutableListOf<ReportFileModel>()
                list.forEach {
                    val r = viewModel.save(it.url, it.file.name)
                    if (r.isSuccessful) {
                        l.add(it)
                    }
                }
                hideLoading()
                if (l.size == list.size) {
                    showToast("保存成功")
                    finish()
                } else {
                    list.removeAll(list)
                    adapter.notifyDataSetChanged()
                    showToast("部分文件保存失败，请重试")
                }
            }
        }
        lifecycleScope.launch {
            val r = viewModel.getList()
            if (r.isSuccessful) {
                r.data?.let {
                    list.clear()
                    list.addAll(it.map {
                        ReportFileModel(it.content ?: "").apply {
                            reportModel = it
                        }
                    })
                    adapter.notifyDataSetChanged()
                }
            }
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data != null && requestCode == 1000 && resultCode == Activity.RESULT_OK) {
            val d = data.getParcelableExtra<ReportFileModel>("data")
            if (d != null) {

                uploadFile(d)
            }
        }
        if (requestCode == 1001 && resultCode == RESULT_OK) {
            val d = PictureSelector.obtainSelectorList(data)
            d.forEach {
                uploadFile(ReportFileModel(it.realPath))
            }
        }
    }

    private fun uploadFile(d: ReportFileModel) {
        lifecycleScope.launch {
            showLoading()
            val r = upload(d.file)
            if (r.isSuccessful) {
                val m = viewModel.save(r.data?.url, d.file.name)
                if (m.isSuccessful) {
                    showToast("上传成功")
                    d.reportModel = m.data
                    list.add(d)
                    adapter.notifyDataSetChanged()
                } else {
                    showToast("上传失败，" + m.msg)
                }
            } else {
                showToast("上传失败，" + r.msg)
            }
            hideLoading()
        }
    }

    private inner class UploadFileAdapter : Adapter<UploadFileViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UploadFileViewHolder {
            return UploadFileViewHolder(
                layoutInflater.inflate(
                    R.layout.list_item_upload_file,
                    parent,
                    false
                )
            )
        }

        override fun getItemCount(): Int {
            return list.size
        }

        override fun onBindViewHolder(holder: UploadFileViewHolder, position: Int) {
            val item = list[position]
            holder.vb.let {
                it.filename.text = item.name
                it.thumbnai.loadUrl(item.imageUrl)
                it.root.onClick {
                    ImagePreviewActivity.start(this@SendReportActivity, item.path)
                }
                it.remove.onClick {
                    if (item.isServerData) {
                        lifecycleScope.launch {
                            showLoading()
                            val r = Request.postSuspend<Any>(
                                "api/report/delete", mapOf("id" to item.reportModel?.id)
                            )
                            hideLoading()
                            if (r.isSuccessful) {
                                list.removeAt(position)
                                notifyDataSetChanged()
                                showToast("删除成功")
                            } else {
                                showToast("删除失败，" + r.msg)
                            }
                        }
                        return@onClick
                    }
                    list.removeAt(position)
                    notifyDataSetChanged()
                }
            }
        }

    }

    private class UploadFileViewHolder(itemView: View) : ViewHolder(itemView) {
        val vb = ListItemUploadFileBinding.bind(itemView)
    }

    private fun showSelectDialog() {
        ChooseGalleryDialog(this).show()
//        val d = AlertDialog.Builder(this)
//            .setItems(arrayOf("相机", "相册"), object : DialogInterface.OnClickListener {
//                override fun onClick(dialog: DialogInterface?, which: Int) {
//                    when (which) {
//                        0 -> {
//                            openCamera()
//                        }
//
//                        1 -> {
//                            pictureSelector()
//                        }
//                    }
//                }
//
//            }).show()
//        lifecycleScope.launch {
//            delay(100)
//            setTextSize(d.findViewById(android.R.id.content))
//        }

    }

    private fun setTextSize(view: View?) {
        view ?: return
        if (view is TextView) {
            view.textSize = 32f
        } else if (view is ViewGroup) {
            view.children.forEach {
                setTextSize(it)
            }
        }
    }

    fun openCamera() {
        val dir = File(filesDir.absolutePath + "/photo/")
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val file = File(
            dir,
            System.currentTimeMillis().toString() + ".jpg"
        )
        lastUri = file
        val uri = FileProvider.getUriForFile(
            this@SendReportActivity,
            packageName,
            file
        )
        camera.launch(uri)
    }

    fun pictureSelector() {
        PictureSelectorFragment.name = loginViewModel.personalInfo.value?.name ?: ""
        PictureSelector.create(this).openGallery(SelectMimeType.TYPE_IMAGE).setImageSpanCount(3)
            .isDisplayCamera(false).isPageStrategy(false)
            .setMaxSelectNum(9).isDirectReturnSingle(true)
            .setImageEngine(GlideEngine).forResult(1001)
    }

}